package com.efounder.frame.xmlparse;

import android.content.Context;

import com.core.xml.StubObject;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by XinQing on 2016/8/25.
 */

public class EFXmlViewTypeParser {

    private static Map<String,StubObject> viewTypeMap = new HashMap<>();


    private static void parseViewTypeXML(Context context){
        try {
            InputStream inputStream = context.getAssets().open("view_type.xml");
            parseViewTypeXML(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private static void parseViewTypeXML(InputStream inputStream){
        //首先得到：得到 DOM 解析器的工厂实例
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(inputStream);
            NodeList nodeList = document.getElementsByTagName("node");
            for (int i=0; i<nodeList.getLength(); i++){
                Node node = nodeList.item(i);
                switch (node.getNodeType()){
                    case Node.ELEMENT_NODE:
                        Element nodeElement = (Element) node;
                        String viewType = nodeElement.getAttribute(EFXmlConstants.ATTR_VIEW_TYPE);
                        NamedNodeMap attrs = nodeElement.getAttributes();
                        StubObject stubObject = new StubObject();
                        for (int j=0; j<attrs.getLength(); j++){
                            Node attr = attrs.item(j);
                            stubObject.setString(attr.getNodeName(),attr.getNodeValue());
                        }
                        viewTypeMap.put(viewType,stubObject);
                        break;
                    case Node.TEXT_NODE:
                        break;
                    case Node.COMMENT_NODE:
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 根据viewType类型，获取xml中配置的数据
     * @param context
     * @param viewType
     * @return
     */
    public static StubObject getStubByViewType(Context context, String viewType){
        if (viewTypeMap.size() == 0){
            parseViewTypeXML(context);
        }
        return viewTypeMap.get(viewType);
    }

}
